package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeProvinceOrderWindow;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.AsyncDimFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/1/10 14:42
 */
public class Dws_10_DwsTradeProvinceOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_10_DwsTradeProvinceOrderWindow().init(
            4010,
            2,
            "Dws_10_DwsTradeProvinceOrderWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TradeProvinceOrderWindow> streamWithoutDim = stream
            .map(new MapFunction<String, TradeProvinceOrderWindow>() {
                @Override
                public TradeProvinceOrderWindow map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeProvinceOrderWindow.builder()
                        .provinceId(obj.getString("province_id"))
                        .orderDetailId(obj.getString("id"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .orderIdSet(new HashSet<>(Collections.singletonList(obj.getString("order_id"))))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
                }
            
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(TradeProvinceOrderWindow::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeProvinceOrderWindow, TradeProvinceOrderWindow>() {
                private ValueState<TradeProvinceOrderWindow> beanState;
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    beanState = getRuntimeContext().getState(new ValueStateDescriptor<TradeProvinceOrderWindow>("bean", TradeProvinceOrderWindow.class));
                }
            
                @Override
                public void processElement(TradeProvinceOrderWindow currentBean,
                                           Context ctx,
                                           Collector<TradeProvinceOrderWindow> out) throws Exception {
                    TradeProvinceOrderWindow lastBean = beanState.value();
                    // 1. 把这个数据发送到下游
                    // 1.1 如果是第一条, 直接发
                    // 1.2 如果不是第一条则需要用新数据,减去状态中的数据
                    if (lastBean == null) {
                        out.collect(currentBean);
                    } else { // 不是第一条
                        // 新值减旧值
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        out.collect(lastBean);
                    }
                    // 2. 先把数据存入到状态中
                    beanState.update(currentBean);
                
                }
            })
            .keyBy(TradeProvinceOrderWindow::getProvinceId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow value1,
                                                           TradeProvinceOrderWindow value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                    @Override
                    public void process(String provinceId,
                                        Context context,
                                        Iterable<TradeProvinceOrderWindow> elements,
                                        Collector<TradeProvinceOrderWindow> out) throws Exception {
                        TradeProvinceOrderWindow bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(context.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(context.window().getEnd()));
                    
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            );
    
        AsyncDataStream.unorderedWait(
                streamWithoutDim,
                new AsyncDimFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public String getTable() {
                        return "dim_base_province";
                    }
                
                    @Override
                    public String getId(TradeProvinceOrderWindow input) {
                        return input.getProvinceId();
                    }
                
                    @Override
                    public void addDim(TradeProvinceOrderWindow input, JSONObject dim) {
                        input.setProvinceName(dim.getString("NAME"));
                    }
                },
                120,
                TimeUnit.SECONDS
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_province_order_window", TradeProvinceOrderWindow.class));
    
    }
}
/*
交易域省份粒度下单各窗口汇
统计各省份各窗口订单数和订单金额
数据源:
    dwd 下单明细表
    
去重:
    按照详情 id 去重
    
开窗聚合
    聚和金额
    
    订单数:
        order_detail_id  order_id  ....      订单数
        10                  1                   1
        11                  1                   0
        
      把order_id 存储到一个 set 集合中
      
      在最后, set 集合的长度, 就是订单数
        
    
补充维度信息
写出到 clickhouse
 */